﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Text.Encodings.Web;
using System.Text.Json;
using WeChatBotSDK.Events;
using WeChatBotSDK.Models.EventCallback;

namespace WeChatBotSDK.Controllers
{
    /// <summary>
    /// 接收和处理微信回调的控制器。
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class QXWechatCallbackController : ControllerBase
    {
        private readonly ILogger<QXWechatCallbackController> _logger;
        private readonly JsonSerializerOptions options;

        /// <summary>
        /// 构造函数，注入日志记录器。
        /// </summary>
        /// <param name="logger">用于记录日志的 <see cref="ILogger"/> 实例。</param>
        public QXWechatCallbackController(ILogger<QXWechatCallbackController> logger)
        {
            _logger = logger;
            options = new JsonSerializerOptions
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };
        }

        /// <summary>
        /// 接收微信回调数据并分发到相应的事件处理逻辑。
        /// </summary>
        /// <param name="callback">微信事件回调数据。</param>
        /// <returns>处理结果的 HTTP 响应。</returns>
        [HttpPost("ReceiveCallback")]
        public IActionResult ReceiveCallback([FromBody] EventCallback<object> callback)
        {
            if (callback == null || callback.Event == WechatEventType.Unknown || callback.Data == null)
            {
                _logger.LogWarning("收到无效的回调数据或未知事件类型");
                return BadRequest("无效的回调数据或未知事件类型");
            }

            try
            {
                switch (callback.Event)
                {
                    case WechatEventType.InjectionSuccess:
                        var res_InjectionSuccess = JsonSerializer.Deserialize<EventCallback<EventData<InjectionSuccessEventData>>>(JsonSerializer.Serialize(callback, options));
                        EventHandlers.OnInjectionSuccess?.Invoke(res_InjectionSuccess);
                        break;

                    case WechatEventType.TransferEvent:
                        var res_TransferEvent = JsonSerializer.Deserialize< EventCallback<EventData<TransferEventData>>>(JsonSerializer.Serialize(callback, options));
                        EventHandlers.OnTransferEvent?.Invoke(res_TransferEvent);
                        break;

                    case WechatEventType.PaymentEvent:
                        var res_PaymentEvent = JsonSerializer.Deserialize< EventCallback<EventData<PaymentEventData>>>(JsonSerializer.Serialize(callback, options));
                        EventHandlers.OnPaymentEvent?.Invoke(res_PaymentEvent);
                        break;

                    case WechatEventType.GroupMessageReceived:
                    case WechatEventType.SelfMessageSent:
                    case WechatEventType.PrivateMessageReceived:
                        var res_Message = JsonSerializer.Deserialize< EventCallback<EventData<WeChatMessageData>>>(JsonSerializer.Serialize(callback, options));
                        EventHandlers.OnMessage?.Invoke(res_Message);
                        break;

                    case WechatEventType.FriendRequest:
                        var res_FriendRequest = JsonSerializer.Deserialize< EventCallback<EventData<FriendRequestData>>>(JsonSerializer.Serialize(callback, options));
                        EventHandlers.OnFriendRequest?.Invoke(res_FriendRequest);
                        break;

                    case WechatEventType.AccountChangeEvent:
                        var res_AccountChangeEvent = JsonSerializer.Deserialize< EventCallback<WeChatUserInfoData>>(JsonSerializer.Serialize(callback, options));
                        Debug.WriteLine(res_AccountChangeEvent);
                        EventHandlers.OnAccountChangeEvent?.Invoke(res_AccountChangeEvent);
                        break;

                    default:
                        _logger.LogWarning("收到暂不支持的事件类型");
                        return BadRequest("暂不支持的事件类型");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理微信回调消息时发生错误");
                return StatusCode(500, "服务器内部错误");
            }

            return Ok("回调数据已处理");
        }
    }
}
